package com.wzdigit.wms.common.utils;


import com.wzdigit.wms.common.entity.FastDFSFile;
import org.csource.common.NameValuePair;
import org.csource.fastdfs.*;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

public class FastDFSUtil {

	public static void main(String[] args) {
		File files = new File("E:\\WEIZHI\\WMS\\xlsx");
		for (File file : files.listFiles()) {
			FastDFSFile fastDFSFile = new FastDFSFile();
			fastDFSFile.setContent(File2byte(file));
			fastDFSFile.setName(file.getName());
			fastDFSFile.setExt("xlsx");
			String[] upload = upload(fastDFSFile);
			System.out.println(file.getName());
			System.out.println(upload[0] + "/" + upload[1]);
		}
	}
	
	/**
     * 将文件转换成byte数组
     * @param file
     * @return
     */
	public static byte[] File2byte(File file) {
		byte[] buffer = null;
		try {
			FileInputStream fis = new FileInputStream(file);
			ByteArrayOutputStream bos = new ByteArrayOutputStream();
			byte[] b = new byte[1024];
			int n;
			while ((n = fis.read(b)) != -1) {
				bos.write(b, 0, n);
			}
			fis.close();
			bos.close();
			buffer = bos.toByteArray();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return buffer;
	}

    /***
     * 初始化tracker信息
     */
    static {
        try {
            ClientGlobal.initByProperties("fastdfs/fastdfs-client.properties");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /****
     * 文件上传
     * @param file : 要上传的文件信息封装->FastDFSFile
     * @return String[]
     *          1:文件上传所存储的组名
     *          2:文件存储路径
     */
    public static String[] upload(FastDFSFile file) {
        //获取文件作者
        NameValuePair[] meta_list = new NameValuePair[1];
        meta_list[0] = new NameValuePair("Author", file.getAuthor());

        /***
         * 文件上传后的返回值
         * uploadResults[0]:文件上传所存储的组名，例如:group1
         * uploadResults[1]:文件存储路径,例如：M00/00/00/wKjThF0DBzaAP23MAAXz2mMp9oM26.jpeg
         */
        String[] uploadResults = null;
        try {
            TrackerServer trackerServer = getTrackerServer();
            //获取StorageClient对象
            StorageClient storageClient = new StorageClient(trackerServer, null);
            //执行文件上传
            /**
             * 返回两个参数
             *    * <ul><li>results[0]: 文件上传所存储的的Storage的组名字 group1
             *    * <ul><li>results[1]: 文件存储到Storage上的名字        MOO/02/44/xx.jpg
             */
            uploadResults = storageClient.upload_file(file.getContent(), file.getExt(), meta_list);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return uploadResults;
    }

    /**
     * 多文件上传
     * 返回两个参数
     * <ul><li>results[0]: 文件上传所存储的的Storage的组名字 group1
     * <ul><li>results[1]: 文件存储到Storage上的名字        MOO/02/44/xx.jpg
     *
     * @param files
     * @return List String[]
     * 1:文件上传所存储的组名
     * 2:文件存储路径
     */
    public static List<String[]> moreFileUpload(List<FastDFSFile> files) {
        List<String[]> resultList = new ArrayList<>();
        for (FastDFSFile file : files) {
            //获取文件作者
            NameValuePair[] meta_list = new NameValuePair[1];
            meta_list[0] = new NameValuePair("Author", file.getAuthor());

            /***
             * 文件上传后的返回值
             * uploadResults[0]:文件上传所存储的组名，例如:group1
             * uploadResults[1]:文件存储路径,例如：M00/00/00/wKjThF0DBzaAP23MAAXz2mMp9oM26.jpeg
             */
            String[] uploadResults = null;
            try {
                TrackerServer trackerServer = getTrackerServer();
                //获取StorageClient对象
                StorageClient storageClient = new StorageClient(trackerServer, null);
                //执行文件上传
                /**
                 * 返回两个参数
                 *    * <ul><li>results[0]: 文件上传所存储的的Storage的组名字 group1
                 *    * <ul><li>results[1]: 文件存储到Storage上的名字        MOO/02/44/xx.jpg
                 */
                uploadResults = storageClient.upload_file(file.getContent(), file.getExt(), meta_list);
                resultList.add(uploadResults);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return resultList;
    }


    /***
     * 获取Tracker服务地址
     */
    public static String getTrackerUrl() throws Exception {
        try {
            TrackerServer trackerServer = getTrackerServer();
            //获取Tracker地址
            return "http://" + trackerServer.getInetSocketAddress().getHostString() + ":" + ClientGlobal.getG_tracker_http_port();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /***
     * 获取TrackerServer
     */
    public static TrackerServer getTrackerServer() throws Exception {
        //创建TrackerClient对象
        TrackerClient trackerClient = new TrackerClient();
        //通过TrackerClient获取TrackerServer对象
        TrackerServer trackerServer = trackerClient.getConnection();
        return trackerServer;
    }

    /***
     * 获取StorageClient
     * @return
     * @throws Exception
     */
    public static StorageClient getStorageClient() throws Exception {
        //获取TrackerServer
        TrackerServer trackerServer = getTrackerServer();
        //通过TrackerServer创建StorageClient
        StorageClient storageClient = new StorageClient(trackerServer, null);
        return storageClient;
    }

    /***
     * 获取文件信息
     * @param groupName:组名
     * @param remoteFileName：文件存储完整名
     */
    public static FileInfo getFile(String groupName, String remoteFileName) {
        try {
            //获取StorageClient对象
            StorageClient storageClient = getStorageClient();
            //获取文件信息
            return storageClient.get_file_info(groupName, remoteFileName);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /***
     * 获取组信息
     * @param groupName :组名
     */
    public static StorageServer getStorages(String groupName) {
        try {
            //创建TrackerClient对象
            TrackerClient trackerClient = new TrackerClient();
            //通过TrackerClient获取TrackerServer对象
            TrackerServer trackerServer = trackerClient.getConnection();
            //通过trackerClient获取Storage组信息
            return trackerClient.getStoreStorage(trackerServer, groupName);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static StorageServer getStorages() {
        try {
            //创建TrackerClient对象
            TrackerClient trackerClient = new TrackerClient();
            //通过TrackerClient获取TrackerServer对象
            TrackerServer trackerServer = trackerClient.getConnection();
            //通过trackerClient获取Storage组信息
            return trackerClient.getStoreStorage(trackerServer);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /***
     * 文件下载
     * @param groupName:组名
     * @param remoteFileName：文件存储完整名
     * @return
     */
    public static InputStream downFile(String groupName, String remoteFileName) {
        try {
            //获取StorageClient
            StorageClient storageClient = getStorageClient();
            //通过StorageClient下载文件
            byte[] fileByte = storageClient.download_file(groupName, remoteFileName);
            //将字节数组转换成字节输入流
            return new ByteArrayInputStream(fileByte);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /***
     * 文件删除实现
     * @param groupName:组名
     * @param remoteFileName：文件存储完整名
     */
    public static Integer deleteFile(String groupName, String remoteFileName) {
        try {
            //获取StorageClient
            StorageClient storageClient = getStorageClient();
            //通过StorageClient删除文件
            return storageClient.delete_file(groupName, remoteFileName);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /***
     * 根据文件组名和文件存储路径获取Storage服务的IP、端口信息
     * @param groupName :组名
     * @param remoteFileName ：文件存储完整名
     */
    public static ServerInfo[] getServerInfo(String groupName, String remoteFileName) {
        try {
            //创建TrackerClient对象
            TrackerClient trackerClient = new TrackerClient();
            //通过TrackerClient获取TrackerServer对象
            TrackerServer trackerServer = trackerClient.getConnection();
            //获取服务信息
            return trackerClient.getFetchStorages(trackerServer, groupName, remoteFileName);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


//    public static void main(String[] args) throws IOException {
//        FileInfo file = getFile("group1", "M00/00/00/rBAZ9V6AHRGAM7ENAA-df26FDk0489.jpg");
//        System.out.println(file.getCrc32());
//        System.out.println(file.getFileSize());
//        System.out.println(file.getFileSize()/1024);
//        System.out.println(file.getSourceIpAddr());
//        InputStream inputStream = downFile("group1", "M00/00/00/rBAZ9V5bo6eAKfwUAA-df26FDk0402.jpg");
//
//        byte[] buffer = new byte[2];
//
//        String path = "/Users/yangwenbiao/1.jpg";
//        FileOutputStream fileOutputStream = new FileOutputStream(path);
//
//        while (inputStream.read(buffer) != -1) {
//            fileOutputStream.write(buffer);
//        }
//
//        fileOutputStream.flush();
//        fileOutputStream.close();
//        inputStream.close();
//
//        deleteFile("group1","M00/00/00/rBAZ9V6AHRGAM7ENAA-df26FDk0489.jpg");
//        System.out.println("删除成功");

//        StorageServer storages = getStorages();
//        System.out.println(storages);
//        System.out.println(storages.getStorePathIndex());
//        System.out.println(storages.getInetSocketAddress());
//
//        StorageServer storages1 = getStorages("group1");
//        System.out.println(storages1.getStorePathIndex());
//        System.out.println(storages1.getInetSocketAddress());

//        ServerInfo[] serverInfo = getServerInfo("group1","M00/00/00/rBAZ9V5bo6eAKfwUAA-df26FDk0402.jpg");
//
//        System.out.println(serverInfo.length);
//
//        System.out.println(serverInfo[0].getIpAddr());
//        System.out.println(serverInfo[0].getPort());

//        String trackerUrl = getTrackerUrl();
//        System.out.println(trackerUrl);
//    }
}